package com.tous.tool.controller;


import com.tous.tool.protobuf.Persion;
import org.springframework.http.MediaType;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 73578
 */
@RestController
@RequestMapping("/api/persons")
public class PersonController {

    private final List<Persion.Person> personList = new ArrayList<>();

    // 创建Person
    @PostMapping(consumes = { MediaType.APPLICATION_PROTOBUF_VALUE, MediaType.APPLICATION_JSON_VALUE })
    public void createPerson(@RequestBody Persion.Person person) {
        personList.add(person);
    }

    // 获取所有Person
    @GetMapping(produces = { MediaType.APPLICATION_PROTOBUF_VALUE, MediaType.APPLICATION_JSON_VALUE })
    public Persion.AddressBook getAllPersons() {
        Persion.AddressBook.Builder addressBook = Persion.AddressBook.newBuilder();
        addressBook.addAllPeople(personList);
        return addressBook.build();
    }

    // 根据ID获取Person
    @GetMapping(value = "/{id}", produces = { MediaType.APPLICATION_PROTOBUF_VALUE, MediaType.APPLICATION_JSON_VALUE })
    public Persion.Person getPersonById(@PathVariable int id) {
        return personList.stream()
                .filter(person -> person.getId() == id)
                .findFirst()
                .orElse(null);
    }


}    